I am trying to update a React.useState("") using setDisplay in a function that takes an array of strings and joined them into a single string before setDisplay.
Without the setDisplay, I'm able to console.log() and get the joined array.
const App = () => {
const [display, setDisplay] = React.useState("");
const values = [];
const onClick = (value) => {
values.push(value);
console.log(values) // w/o setDisplay output: ["1","2","3","4"]; w/ setDisplay output: ["1"]; ["2"]; ["3"]; ["4"];
setDisplay(values.join(""))
};
return (
<div className="p-5">
{display}
<NumPads data={keypress} onClick={onClick} />
<OperatorPads data={keypress} onClick={onClick} />
</div>
);
};
setDisplay((values) => ([...values, value].join("")]))
const onClick = (value) => setDisplay((dispay) => display.concat('', value));
The reason the console.log seems to work when you don't call setDisplay is simply because the state of the component did not change.
When you call setDisplay, you change the state, so the entire component re-renders, which causes values to reset back to an empty array.
One way to solve this is already shown in a previous answer.
Another way is to wrap your values array with useRef:
const values = useRef([]);
Then access the array using values.current
Yet another way is to eliminate the use of values all together and change the callback to:
const onClick = (value) => {
setDisplay(display + value);
};